package com.wang.thread;

import com.wang.util.TokenBucket;

import java.util.LinkedList;
import java.util.UUID;

/**
 * 令牌定时存放
 * Created by wang on 2017/5/3.
 */
public class SetTokenTimer implements Runnable {
    private final LinkedList<UUID> list;

    public SetTokenTimer(LinkedList<UUID> list) {
        this.list = list;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (list) {
                //如果超额，线程等待
                if (list.size() >= 100) {
                    try {
                        list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    list.notify();
                }
            }
            try {
                //设置存放令牌间隔
                Thread.sleep(800);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(list.size()<100)
            TokenBucket.setToken();
            synchronized (list) {
                list.notify();
            }
            System.out.println("桶内剩余：" + TokenBucket.getTokenNum()+"块令牌");
        }

    }
}
